/**
* @depends jquery.ui.js
*/

(function($) {

	$.widget( 'ui.widget_tabpane', {
		
		_init: function() {
		
			var $this = this;
		
			$('.TabTitles li', this.element).mousedown( function() {
				$this.select( $(this) );
			} );
			
			this._load( $('> .TabContents > li.Current', this.element) );
			
			return this;
		},
		
		_load: function( tab ) {
			var action = tab.attr( 'action' );
			if( !action ) {
				return this;
			}
			tab.removeAttr( 'action' );
			$.wajax( action, function( json ) {
				if( json.status != 'success' ) {
					return false;
				}
				var content = $(json.content);
				tab.html( content );
				tab.main();
			} );
		},
		
		select: function( o ) {
		
			if( o.hasClass( 'Current' ) ) {
				return this;
			}
			
			var tabPane = this.element;
			this.unselect( o.closest( '.TabTitles' ).find( '.Current' ) );
			var nth = o.prevAll().length + 1;
			tabPane
				.find( '> ul > li:nth-child(' + nth + ')' )
				.addClass( 'Current' );
			
			this._load( $('> .TabContents > li.Current', this.element) );
			o.triggerHandler( 'tabpane-tab-select' );
			return this;
		},
		
		unselect: function( o ) {
			if( !o.hasClass( 'Current' ) ) {
				return this;
			}
			
			var tabPane = this.element;
			var nth = o.prevAll().length + 1;
			tabPane
				.find( '> ul > li:nth-child(' + nth + ')' )
				.removeClass( 'Current' );
			
			o.triggerHandler( 'tabpane-tab-unselect' );
			return this;
		}
		
	} );
	
})(jQuery);
